package com.hyl.domain.trade.service.settlement.filter;

import com.hyl.domain.trade.adapter.repository.ITradeRepository;
import com.hyl.domain.trade.model.entity.GroupBuyTeamEntity;
import com.hyl.domain.trade.model.entity.MarketPayOrderEntity;
import com.hyl.domain.trade.model.entity.TradeSettlementRuleCommandEntity;
import com.hyl.domain.trade.model.entity.TradeSettlementRuleFilterBackEntity;
import com.hyl.domain.trade.service.settlement.factory.TradeSettlementRuleFilterFactory;
import com.hyl.types.design.framework.link.moudle2.handler.ILogicHandler;
import com.hyl.types.enums.ResponseCode;
import com.hyl.types.exception.AppException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @author hyl
 * @description 判断交易时间是否在规定时间进行过滤
 * @create 2025-07-04 17:16
 */
@Slf4j
@Service
public class SettableRuleFilter implements ILogicHandler<TradeSettlementRuleCommandEntity, TradeSettlementRuleFilterFactory.DynamicContext, TradeSettlementRuleFilterBackEntity> {

    @Resource
    private ITradeRepository repository;
    @Override
    public TradeSettlementRuleFilterBackEntity apply(TradeSettlementRuleCommandEntity requestParameter, TradeSettlementRuleFilterFactory.DynamicContext dynamicContext) throws Exception {

        log.info("交易规则过滤-可结算时间判断{}", requestParameter.getUserId());
        //获得上下文信息
        MarketPayOrderEntity marketPayOrderEntity = dynamicContext.getMarketPayOrderEntity();

        //查询拼团对象
        GroupBuyTeamEntity groupBuyTeamEntity = repository.queryGroupBuyTeamByTeamId(marketPayOrderEntity.getTeamId());

        //外部交易时间
        Date outTradeTime = requestParameter.getOutTradeTime();

        //判断，外部交易时间要小于拼团交易时间，否则抛出异常
        if(!outTradeTime.before(groupBuyTeamEntity.getValidEndTime())){
            log.error("订单交易时间不在拼团有效时间范围内");
            throw new AppException(ResponseCode.E0106);
        }
        //设置上下文
        dynamicContext.setGroupBuyTeamEntity(groupBuyTeamEntity);

        return next(requestParameter, dynamicContext);
    }
}
